package com.zzzy.cont.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzzy.common.enums.YesOrNoEnum;
import com.zzzy.common.exception.BusinessException;
import com.zzzy.common.util.AssertUtil;
import com.zzzy.common.util.FileUtil;
import com.zzzy.cont.dao.entity.ConFile;
import com.zzzy.cont.dao.entity.ConFileTemplate;
import com.zzzy.cont.dao.mapper.ConFileMapper;
import com.zzzy.framework.common.enums.common.TemplateStatusEnum;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Objects;

/**
 * 合同文件信息 服务实现类
 *
 * @author fc
 * @since 2024-05-27
 */
@Service
public class ConFileService extends ServiceImpl<ConFileMapper, ConFile> {

    @Resource
    private ConFileTemplateService conFileTemplateService;
    @Resource
    private ConFileHistoryService conFileHistoryService;

    public void addConFileByTemplateId(Long conId, Long templateId) {
        ConFile conFile = new ConFile();
        conFile.setConId(conId);
        ConFileTemplate template = conFileTemplateService.getConFileTemplateByIdForQuery(templateId);
        AssertUtil.isEquals(TemplateStatusEnum.ENABLE.getValue(), template.getStatus(), "合同文件模板状态错误");
        conFile.setTemplateName(template.getName());
        conFile.setWordFileBlob(template.getFileBlob());
        conFile.setIsFixedFormat(template.getIsFixedFormat());
        conFile.setDataRegions(template.getDataRegions());
        baseMapper.insert(conFile);
        //添加合同文件历史备份
        conFileHistoryService.addInitHistory(conId);
    }

    public void addConFileByUploadFile(Long conId, MultipartFile uploadFile) {
        byte[] byteFileBlob;
        try {
            byteFileBlob = uploadFile.getBytes();
        } catch (IOException e) {
            throw new BusinessException("文件读取错误");
        }
        ConFile conFile = new ConFile();
        conFile.setConId(conId);
        conFile.setIsFixedFormat(YesOrNoEnum.NO.getValue());
        String fileType = uploadFile.getOriginalFilename().substring(uploadFile.getOriginalFilename().lastIndexOf(".") +1);
        AssertUtil.isTrue(!FileUtil.isChangeFileExtendType(fileType, byteFileBlob), "上传的文件手动修改过文件扩展名,请另存文件后重试");
        if (FileUtil.PDF.equalsIgnoreCase(fileType)) {
            conFile.setPdfFileBlob(byteFileBlob);
        } else {
            conFile.setWordFileBlob(byteFileBlob);
        }
        baseMapper.insert(conFile);
        //添加合同文件历史备份
        conFileHistoryService.addInitHistory(conId);
    }

    /**
     * 更新已有合同文件为上传的文件
     */
    public void updateConFileByUploadFile(Long conId, MultipartFile uploadFile) {
        byte[] byteFileBlob;
        try {
            byteFileBlob = uploadFile.getBytes();
        } catch (IOException e) {
            throw new BusinessException("文件读取错误");
        }
        String fileType = uploadFile.getOriginalFilename().substring(uploadFile.getOriginalFilename().lastIndexOf(".") +1);
        AssertUtil.isTrue(FileUtil.checkIsContract(byteFileBlob), "文件非合同类型文件");
        if (!FileUtil.DOC.equalsIgnoreCase(fileType) && !FileUtil.DOCX.equalsIgnoreCase(fileType) && !FileUtil.PDF.equalsIgnoreCase(fileType)){
            throw new BusinessException("上传文件类型不符，请上传扩展名为 doc, docx, pdf的有效合同文件。");
        }
        AssertUtil.isTrue(!FileUtil.isChangeFileExtendType(fileType, byteFileBlob), "上传的文件手动修改过文件扩展名,请另存文件后重试");
        ConFile conFile = getConFileByConId(conId);
        conFile.setIsFixedFormat(YesOrNoEnum.NO.getValue());
        if (FileUtil.PDF.equalsIgnoreCase(fileType)) {
            conFile.setPdfFileBlob(byteFileBlob);
            conFile.setWordFileBlob(null);
        } else {
            conFile.setWordFileBlob(byteFileBlob);
            conFile.setPdfFileBlob(null);
        }
        baseMapper.updateById(conFile);

        //清除历史记录 重新添加
        conFileHistoryService.clearHistoryByConId(conId);
        conFileHistoryService.addInitHistory(conId);
    }

    public void updateConFileByTemplateId(Long conId, Long templateId) {
        ConFile conFile = getConFileByConId(conId);
        ConFileTemplate template = conFileTemplateService.getConFileTemplateByIdForQuery(templateId);
        AssertUtil.isEquals(TemplateStatusEnum.ENABLE.getValue(), template.getStatus(), "合同文件模板状态错误");

        conFile.setTemplateName(template.getName());
        conFile.setWordFileBlob(template.getFileBlob());
        conFile.setIsFixedFormat(template.getIsFixedFormat());
        conFile.setPdfFileBlob(null);
        conFile.setDataRegions(template.getDataRegions());
        baseMapper.updateById(conFile);
        //清除历史记录 重新添加
        conFileHistoryService.clearHistoryByConId(conId);
        conFileHistoryService.addInitHistory(conId);
    }

    public void updateWordByConId(Long conId, byte[] byteArray, Integer revisionCount) {
        ConFile conFile = getConFileByConId(conId);
        conFile.setWordFileBlob(byteArray);
        conFile.setRevisionCount(revisionCount);
        baseMapper.updateById(conFile);
    }

    public void updatePdfByConId(Long conId, byte[] byteArray) {
        ConFile conFile = getConFileByConId(conId);
        conFile.setPdfFileBlob(byteArray);
        baseMapper.updateById(conFile);
    }

    public ConFile getConFileByConId(Long conId) {
        ConFile conFile = baseMapper.selectOne(new LambdaQueryWrapper<ConFile>().eq(ConFile::getConId, conId));
        AssertUtil.nonNull(conFile, "合同文件不存在");
        return conFile;
    }

    public void clearPdfIfHasWord(Long conId) {
        ConFile conFile = getConFileByConId(conId);
        if (Objects.nonNull(conFile.getWordFileBlob())){
            conFile.setPdfFileBlob(null);
        }
        baseMapper.updateById(conFile);
    }

    public void updateMobilePdfBlob(Long conId, byte[] byteArray) {
        ConFile conFile = getConFileByConId(conId);
        conFile.setMobilePdfBlob(byteArray);
        baseMapper.updateById(conFile);
    }
}
